package com.zy.explore.web.security;

import lombok.val;
import org.springframework.http.HttpHeaders;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletRequest;
import java.util.StringTokenizer;

/**
 * description 
 * 
 * @author administrator
 * @date 2021-05-05 18:22
 */
public class BearerTokenResolver {

    private static final String BEARER = "Bearer ";

    @Nullable
    public ResolvedAuthenticationToken resolve(HttpServletRequest request) {
        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (authorization == null || !authorization.startsWith(BEARER)) {
            return null;
        }

        val bearerToken = authorization.substring(BEARER.length());
        val tokens = new StringTokenizer(bearerToken, "=;");

        String id = null, type = null, clientId = "NotFound";
        while (tokens.hasMoreTokens()) {
            val cookieName = tokens.nextToken().trim();

            if (!tokens.hasMoreTokens()) {
                // 不是成对出现的话，直接返回错误
                return null;
            }
            val cookieValue = tokens.nextToken().trim();

            switch (cookieName) {
                case "id":
                    id = cookieValue;
                    break;
                case "type":
                    type = cookieValue;
                    break;
                case "clientId":
                    clientId = cookieValue;
                    break;
            }
        }

        if (null == id || null == type) {
            return null;
        }

        return new ResolvedAuthenticationToken(id, type, clientId);
    }
}
